<?php

class Application_Model_FacebookApi {
	
	const API_BASE_URL = 'base_url';
	// FQL API endpoints
	const FQL_ENDPOINT = 'fql_url';
	const MFQL_ENDPOINT = 'multiquery_url';
	// Graph API endpoints
	const WALL_FEED = 'wall_url';
	const PROFILE = 'profile_url';
	const NEWS_FEED = 'news_feed_url';
	const PROFILE_PICTURE = 'profile_picture_url';
	const FRIENDS = 'friends_url';
	const MY_LIKES = 'my_likes_url';
	const INBOX_FEED = 'inbox_url';
	const SEARCH = 'search_url';
	
	/**
	 * Facebook API Auth Token
	 * @var string
	 */
	protected $access_token;
	/**
	 * Social Graph API URLs
	 * @param array $graph_urls
	 */
	protected $graph_urls;
	/**
	 * Constructor
	 * @param [string $token]
	 */
	public function __construct( $token=null )
	{
		if ( !empty($token) )
		{
			$this->access_token = $token;
		}
		// Populate URLs
		$this->graph_urls = Zend_Registry::get("api_keys")->facebook->social_graph->toArray();
	}
	/**
	 * Check to see if token is set
	 * @return bool
	 */
	public function hasAccessToken()
	{
		return !empty($this->access_token);
	}
	/**
	 * Return the local access token
	 * @return string
	 */
	public function getAccessToken()
	{
		return $this->access_token;
	}
	/**
	 * Set the local access token
	 * @param string $token
	 */
	public function setAccessToken( $token )
	{
		$this->access_token = $token;
	}
	/**
	 * Get a user's profile
	 * @return mixed
	 */
	public function getProfile()
	{
		$url = $this->graph_urls[self::PROFILE];
		$result = $this->request($url);
		return $result;		
	}
	/**
	 * Get a user's wall feed
	 * @return mixed
	 */
	public function getWallFeed()
	{
		$url = $this->graph_urls[self::WALL_FEED];
		$result = $this->request($url);
		return $result;		
	}
	/**
	 * Perform a request to the Facebook API
	 * @param string $url
	 * @param [string $method]
	 * @param [array $params]
	 * @return mixed
	 */
	private function request($url, $method=Zend_Http_Client::GET, $params=array())
	{
		$httpOptions = new Zend_Config_Ini( APPLICATION_PATH . "/configs/http.ini", APPLICATION_ENV );
		$http = new Zend_Http_Client();
		$http->setConfig($httpOptions);
		$http->setMethod($method);
		
		// Set the oauth token
		$http->setParameterGet('access_token', $this->getAccessToken());
		foreach ($params as $param => $value)
		{
			$http->setParameterGet($param, $value);
		}
		
		// Make the request
		$http->setUri($url);
		$result = $http->request();
		$resultBody = $result->getBody();
		if ( $result->isSuccessful() )
		{
			return $result->getBody();
		}
		else
		{
			$code = $result->getStatus();
		}
		return $result;
	}
}